package com.leo.chapter06;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 用ExectorService来创建一个带有生命周期管理的服务器
 *      ExectorService相比Exector接口增加了生命周期管理，提交更方便
 * @author xuexiaolei
 * @version 2017年10月15日
 */
public class LifecycleWebServer {
    private final int NTHREADS = 100;
    private final ExecutorService exec = Executors.newFixedThreadPool(NTHREADS);

    public void start() throws IOException {
        ServerSocket socket = new ServerSocket(80);
        while (!exec.isShutdown()){
            Socket connection = socket.accept();
            Runnable task = new Runnable() {
                @Override public void run() {
                    handleRequest(connection);
                }
            };
            exec.execute(task);
        }
    }

    public void stop(){
        exec.shutdown();
    }

    /**
     * 正真的处理要求线程安全
     * @param connection
     */
    public static void handleRequest(Socket connection){
        try {
            System.out.println("正在处理");
            Thread.sleep(1000);
            System.out.println("处理完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
